package com.bnq.face

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import java.io.FileOutputStream

object CompressUtil {
    /**
     * 压缩图片到指定尺寸和文件大小
     */
    fun compressImage(
        srcPath: String,
        dstPath: String,
        maxWidth: Int,
        maxHeight: Int,
        quality: Int = 80
    ): Boolean {
        // 第一步：读取原图尺寸
        val opts = BitmapFactory.Options().apply {
            inJustDecodeBounds = true
        }
        BitmapFactory.decodeFile(srcPath, opts)
        val (origW, origH) = opts.outWidth to opts.outHeight

        // 计算 inSampleSize
        opts.inSampleSize = calculateInSampleSize(opts, maxWidth, maxHeight)
        opts.inJustDecodeBounds = false

        // 解码缩放后的 Bitmap
        val bitmap = BitmapFactory.decodeFile(srcPath, opts)
            ?: return false

        // 保存为 JPEG 或 WebP
        FileOutputStream(dstPath).use { os ->
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, os)
        }
        return true
    }

    /** 计算最接近 2 的幂次的 inSampleSize */
    fun calculateInSampleSize(
        options: BitmapFactory.Options,
        reqWidth: Int,
        reqHeight: Int
    ): Int {
        val (h, w) = options.outHeight to options.outWidth
        var inSample = 1
        if (h > reqHeight || w > reqWidth) {
            val halfH = h / 2
            val halfW = w / 2
            while (halfH / inSample >= reqHeight && halfW / inSample >= reqWidth) {
                inSample *= 2
            }
        }
        return inSample
    }

}